﻿// ———————————————————————–
// <copyright file="AddressType.cs" company="The MITRE Corporation">
//    Copyright (c) 2014 The MITRE Corporation. All rights reserved.
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>
// ———————————————————————–
/////////////////////////////////////////////////////////////////////////////////////////////////
// AddressType.cs:
// A data type for a geophysical location described by postal information
// Project: EDXLSharp - NIEMCore
//
// Language:    C#, .NET 4.0
// Platform:    Windows 7, VS 2012
// Author:      Jim Cronin MITRE Bedford

/////////////////////////////////////////////////////////////////////////////////////////////////

// Copyright (c) 2014 The MITRE Corporation. All rights reserved.
//
// NOTICE
// This software was produced for the U. S. Government
// under Contract No. FA8721-09-C-0001, and is
// subject to the Rights in Noncommercial Computer Software
// and Noncommercial Computer Software Documentation Clause
// (DFARS) 252.227-7014 (JUN 1995)

using System;
using System.Collections.Generic;
using System.Xml;


namespace EDXLSharp.NIEMCore
{
  /// <summary>
  /// A data type for a geophysical location described by postal information
  /// </summary>
  public abstract class AddressType : ComplexTypeBase
  {
    /// <summary>
    /// A data concept for a single place or unit at which mail is delivered.
    /// </summary>
    public ICollection<IAddressDeliveryPoint> AddressDeliveryPoints;

    /// <summary>
    /// A name of a city or town.
    /// </summary>
    public LocationCityName LocationCityName;

    /// <summary>
    /// A data concept for a county, parish, vicinage, or other such geopolitical subdivision of a stateCode.
    /// </summary>
    public ILocationCounty LocationCounty;

    /// <summary>
    /// A data concept for a stateCode, commonwealth, province, or other such geopolitical subdivision of a country.
    /// </summary>
    public ILocationState LocationState;

    /// <summary>
    /// A data concept for a country, territory, dependency, or other such geopolitical subdivision of a location.
    /// </summary>
    public ILocationCountry LocationCountry;

    /// <summary>
    /// An identifier of a post office-assigned zone for an address.
    /// </summary>
    public string LocationPostalCode;

    /// <summary>
    /// An identifier of a smaller area within a post office-assigned zone for an address.
    /// </summary>
    public string LocationPostalExtensionCode;

    protected Dictionary<string, Func<XmlNode, IAddressDeliveryPoint>> AddressDeliveryPointParsers;
    protected Dictionary<string, Func<XmlNode, ILocationCounty>> LocationCountyParsers;
    protected Dictionary<string, Func<XmlNode, ILocationState>> LocationStateParsers;
    protected Dictionary<string, Func<XmlNode, ILocationCountry>> LocationCountryParsers;

    public AddressType()
    {
      AddressDeliveryPoints = new List<IAddressDeliveryPoint>();
      AddressDeliveryPointParsers = new Dictionary<string, Func<XmlNode, IAddressDeliveryPoint>>();
      LocationCountyParsers = new Dictionary<string, Func<XmlNode, ILocationCounty>>();
      LocationStateParsers = new Dictionary<string, Func<XmlNode, ILocationState>>();
      LocationCountryParsers = new Dictionary<string, Func<XmlNode, ILocationCountry>>();

      RegisterKnownParsers();
    }

    /// <summary>
    /// Writes this Object to an inline XML Document
    /// </summary>
    /// <param name="xwriter">Valid XMLWriter</param>
    /// <exception cref="System.ArgumentNullException">Thrown if xwriter is null</exception>
    /// <exception cref="EDXLSharp.ValidationException">Thrown if the object fails to validate</exception>
    public override void WriteXML(XmlWriter xwriter)
    {
      if (xwriter == null)
      {
        throw new ArgumentNullException("xwriter");
      }

      this.Validate();

      xwriter.WriteStartElement(this.ElementPrefix, this.ElementName, this.ElementNamespace);

      foreach (IAddressDeliveryPoint ic in this.AddressDeliveryPoints)
      {
        ic.WriteXML(xwriter);
      }

      if (this.LocationCityName != null)
      {
        this.LocationCityName.WriteXML(xwriter);
      }

      if (this.LocationCounty != null)
      {
        this.LocationCounty.WriteXML(xwriter);
      }

      if (this.LocationState != null)
      {
        this.LocationState.WriteXML(xwriter);
      }

      if (this.LocationCountry != null)
      {
        this.LocationCountry.WriteXML(xwriter);
      }

      if (!string.IsNullOrWhiteSpace(this.LocationPostalCode))
      {
        xwriter.WriteElementString("LocationPostalCode", this.LocationPostalCode);
      }

      if (!string.IsNullOrWhiteSpace(this.LocationPostalExtensionCode))
      {
        xwriter.WriteElementString("LocationPostalExtensionCode", this.LocationPostalExtensionCode);
      }

      xwriter.WriteEndElement();
    }

    /// <summary>
    /// Reads this Object's values from an XML nodelist
    /// </summary>
    /// <param name="rootnode">root XML Node of the Object element</param>
    /// <exception cref="System.ArgumentNullException">Thrown if rootnode is null</exception>
    /// <exception cref="System.ArgumentException">Thrown if the rootnode is not the correct type</exception>
    /// <exception cref="EDXLSharp.ValidationException">Thrown if the object fails to validate</exception>
    public override void ReadXML(XmlNode rootnode)
    {
      if (rootnode == null)
      {
        throw new ArgumentNullException("rootnode");
      }

      if (rootnode.LocalName != this.ElementName)
      {
        throw new ArgumentException("Unexpected element name " + rootnode.LocalName + " instead of " + this.ElementName);
      }

      foreach (XmlNode node in rootnode.ChildNodes)
      {
        switch (node.LocalName)
        {
          case "LocationCityName":
            this.LocationCityName = new LocationCityName();
            this.LocationCityName.ReadXML(node);
            break;
          case "LocationPostalCode":
            this.LocationPostalCode = node.InnerText;
            break;
          case "LocationPostalExtensionCode":
            this.LocationPostalExtensionCode = node.InnerText;
            break;
          default:
            if (AddressDeliveryPointParsers.ContainsKey(node.LocalName))
            {
              AddressDeliveryPoints.Add(AddressDeliveryPointParsers[node.LocalName](node));
            }
            else if (LocationCountyParsers.ContainsKey(node.LocalName))
            {
              LocationCounty = LocationCountyParsers[node.LocalName](node);
            }
            else if (LocationStateParsers.ContainsKey(node.LocalName))
            {
              LocationState = LocationStateParsers[node.LocalName](node);
            }
            else if (LocationCountryParsers.ContainsKey(node.LocalName))
            {
              LocationCountry = LocationCountryParsers[node.LocalName](node);
            }
            else
            {
              throw new ArgumentException("Unexpected element " + node.LocalName + " as child of " + this.ElementName);
            }
            break;
        }
      }

      this.Validate();
    }

    /// <summary>
    /// Validates This Message element For Required Values and Conformance
    /// </summary>
    /// <exception cref="EDXLSharp.ValidationException">Thrown if the object fails to validate</exception>
    public override void Validate()
    {
      foreach (IAddressDeliveryPoint adp in AddressDeliveryPoints)
      {
        adp.Validate();
      }

      if (LocationCityName != null)
      {
        LocationCityName.Validate();
      }

      if (LocationCounty != null)
      {
        LocationCounty.Validate();
      }

      if (LocationState != null)
      {
        LocationState.Validate();
      }

      if (LocationCountry != null)
      {
        LocationCountry.Validate();
      }

      //no apparent restrictions on LocationPostalCode or LocationPostalExtensionCode
    }

    protected virtual void RegisterKnownParsers()
    {
      // AddressDeliveryPoint:
      // - AddressBuldingName
      Func<XmlNode, IAddressDeliveryPoint> abnParse = (node) => { AddressBuildingName abn = new AddressBuildingName(); abn.ReadXML(node); return abn; };
      AddressDeliveryPointParsers.Add("AddressBuildingName", abnParse);
      // - LocationStreet
      Func<XmlNode, IAddressDeliveryPoint> lstreetParse = (node) => { LocationStreet ls = new LocationStreet(); ls.ReadXML(node); return ls; };
      AddressDeliveryPointParsers.Add("LocationStreet", lstreetParse);

      // LocationCounty:
      // - LocationCountyCode
      Func<XmlNode, ILocationCounty> lcountyParse = (node) => { return new LocationCountyCode(node.InnerText); };
      LocationCountyParsers.Add("LocationCountyCode", lcountyParse);

      // LocationState:
      // - LocationStateFIPS5_2AlphaCode
      Func<XmlNode, ILocationState> lstateParse = (node) => { return new LocationStateFIPS5_2AlphaCode(node.InnerText); };
      LocationStateParsers.Add("LocationStateFIPS5-2AlphaCode", lstateParse);
      
      // LocationCountry:
      // - LocationCountryFIPS10_4Code
      Func<XmlNode, ILocationCountry> lcountryParse = (node) => { return new LocationCountryFIPS10_4Code(node.InnerText); };
      LocationCountryParsers.Add("LocationCountryFIPS10-4Code", lcountryParse);
    }
  }
}
